<template>
  <div class="personnel-management">
    <!-- 页面标题 -->
<!--    <h1 class="page-title">房屋信息管理</h1>-->

    <!-- 搜索筛选区域 -->
    <div class="search-filters">
      <div class="filter-row">
        <!-- 房屋编号搜索 -->
        <div>
          <span class="search-item">房屋编码</span>
          <input
              v-model="searchForm.houseCode"
              type="text"
              placeholder="请输入房屋编号"
              class="input-field"
          />
        </div>

        <!-- 房屋状态搜索 -->
        <div>
          <span class="search-item">房屋状态</span>
          <select v-model="searchForm.houseStatus" class="select-field">
            <option value="">请选择房屋状态</option>
            <option value="1">有人</option>
            <option value="0">空置</option>
          </select>
        </div>

        <!-- 小区搜索 -->
        <div>
          <span class="search-item">小区</span>
          <select v-model="searchForm.communityName" class="select-field">
            <option value="">请选择小区</option>
            <option value="西湖花园">西湖花园</option>
            <option value="樱花苑">樱花苑</option>
            <option value="翠兰苑">翠兰苑</option>
          </select>
        </div>

        <!-- 单元号搜索 -->
        <div>
          <span class="search-item">单元号</span>
          <select v-model="searchForm.unitNumber" class="select-field">
            <option value="">请选择单元</option>
            <option value="01">01单元</option>
            <option value="02">02单元</option>
            <option value="03">03单元</option>
            <option value="04">04单元</option>
          </select>
        </div>

        <!-- 楼层搜索 -->
        <div>
          <span class="search-item">楼层</span>
          <select v-model="searchForm.floorNumber" class="select-field">
            <option value="">请选择楼层</option>
            <option value="01">1楼</option>
            <option value="02">2楼</option>
            <option value="03">3楼</option>
            <option value="04">4楼</option>
            <option value="05">5楼</option>
          </select>
        </div>

        <!-- 房屋用途搜索 -->
        <div>
          <span class="search-item">房屋用途</span>
          <select v-model="searchForm.housePurpose" class="select-field">
            <option value="">请选择房屋用途</option>
            <option value="住宅">住宅</option>
            <option value="商业">商业</option>
            <option value="办公">办公</option>
          </select>
        </div>

        <button @click="handleSearch" class="btn-primary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPnga03cd43e27317f20428660e14317e35a64a3d907d88f824770f063b2f9fd5f10" alt="搜索" class="btn-icon" />
          搜索
        </button>
        <button @click="handleReset" class="btn-secondary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngd1ee69767e02bb56b7c745624d059b292108792e966600668227ff5d22467bbe" alt="重置" class="btn-icon" />
          重置
        </button>
      </div>
    </div>

    <!-- 分割线 -->
    <div class="divider"></div>

    <!-- 操作按钮组 -->
    <!-- 修改操作按钮组部分 -->
    <div class="operation-buttons">
      <button
          @click="handleAdd"
          :class="['btn-add', { 'btn-selected': operationMode === 'add' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngf1cdfd3741aaeaf19e733deebf065b44a820a4e6e4d83792de3c6e699c670645" alt="新增" class="btn-icon" />
        新增
      </button>

      <button
          @click="handleModeChange('edit')"
          :class="['btn-add', { 'btn-selected': operationMode === 'edit' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="修改" class="btn-icon" />
        修改
      </button>

      <button
          @click="handleModeChange('delete')"
          :class="['btn-add', { 'btn-selected': operationMode === 'delete' }]"
      >
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" class="btn-icon" />
        删除
      </button>

      <!-- 导出按钮 -->
      <button @click="handleExport" class="btn-add">
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="导出" class="btn-icon" />
        导出
      </button>

      <!-- 批量删除按钮 -->
      <button
          v-if="operationMode === 'delete' && selectedHouses.length > 0"
          @click="handleBatchDelete"
          class="btn-batch-delete"
      >
        批量删除 ({{ selectedHouses.length }})
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr class="table-header">
          <!-- 删除模式下显示全选框 -->
          <th v-if="operationMode === 'delete'">
            <input
                type="checkbox"
                @change="handleSelectAll"
                :checked="isAllSelected"
                class="checkbox"
            />
          </th>
          <th>序号</th>
          <th>房屋编码</th>
          <th>小区</th>
          <th>单元号</th>
          <th>楼层</th>
          <th>房间号</th>
          <th>房间状态</th>
          <th>缴费状态</th>
          <th>房屋用途</th>
          <th>房屋面积</th>
          <th>创建时间</th>
          <th>更新时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(house, index) in paginatedHouses" :key="house.id" class="table-row">
          <!-- 删除模式下显示复选框 -->
          <td v-if="operationMode === 'delete'">
            <input
                type="checkbox"
                :value="house.id"
                v-model="selectedHouses"
                class="checkbox"
            />
          </td>
          <td>{{ (pagination.currentPage - 1) * pagination.pageSize + index + 1 }}</td>
          <td>{{ house.houseCode }}</td>
          <td>{{ house.communityName }}</td>
          <td>{{ house.unitNumber }}</td>
          <td>{{ house.floorNumber }}</td>
          <td>{{ house.roomNumber }}</td>
          <td>
            <span :class="getStatusClass(house.houseStatus)">
              {{ house.houseStatus === 1 ? '入住' : '空置' }}
            </span>
          </td>
          <td>
            <span :class="getPaymentStatusClass(house)">
              {{ getPaymentStatusText(house) }}
            </span>
          </td>
          <td>{{ house.housePurpose }}</td>
          <td>{{ house.area }}</td>
          <td>{{ house.createTime }}</td>
          <td>{{ house.updateTime }}</td>
          <td class="action-buttons">
            <!-- 查看按钮 - 始终显示 -->
            <button @click="handleView(house)" class="action-btn" title="查看详情">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="查看" />
            </button>

            <!-- 编辑按钮 - 修改模式下显示 -->
            <button v-if="operationMode === 'edit'" @click="handleEdit(house)" class="action-btn" title="编辑">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng8dd30a7302a6f2ab4df9f28606f440873a476132867bc3718014adf8e7a187da" alt="编辑" />
            </button>

            <!-- 删除按钮 - 删除模式下显示 -->
            <button v-if="operationMode === 'delete'" @click="handleSingleDelete(house)" class="action-btn" title="删除">
              <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="删除" />
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="pagination-info">共 {{ pagination.totalPages }} 页</span>
      <button @click="goToPrevPage" :disabled="pagination.currentPage === 1" class="pagination-btn">上一页</button>
      <button
          v-for="page in visiblePages"
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { 'active': page === pagination.currentPage }]"
      >
        {{ page }}
      </button>
      <button @click="goToNextPage" :disabled="pagination.currentPage === pagination.totalPages" class="pagination-btn">下一页</button>
      <span class="pagination-goto">前往</span>
      <input v-model.number="gotoPage" @keyup.enter="handleGotoPage" class="goto-input" />
      <span>页</span>
    </div>

    <!-- 新增/编辑/查看弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <div class="form-item">
              <label>房屋编码</label>
              <input v-model="currentHouse.houseCode" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>房屋名称</label>
              <input v-model="currentHouse.houseName" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>小区名称</label>
              <input v-model="currentHouse.communityName" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>单元号</label>
              <input v-model="currentHouse.unitNumber" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>楼层</label>
              <input v-model="currentHouse.floorNumber" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>房间号</label>
              <input v-model="currentHouse.roomNumber" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>房屋状态</label>
              <select v-model="currentHouse.houseStatus" :disabled="modalType === 'view'" class="form-input">
                <option :value="0">空置</option>
                <option :value="1">有人</option>
              </select>
            </div>
            <div class="form-item">
              <label>缴费状态</label>
              <select v-model="currentHouse.paymentStatus" :disabled="modalType === 'view' || currentHouse.status === 0" class="form-input">
                <option value="normal">正常</option>
                <option value="overdue">欠费</option>
              </select>
            </div>
            <div class="form-item">
              <label>房屋用途</label>
              <input v-model="currentHouse.housePurpose" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>房屋面积</label>
              <input v-model="currentHouse.area" :disabled="modalType === 'view'" class="form-input" />
            </div>
            <div class="form-item">
              <label>创建时间</label>
              <input v-model="currentHouse.createTime" type="date" disabled class="form-input" />
            </div>
            <div class="form-item">
              <label>更新时间</label>
              <input v-model="currentHouse.updateTime" type="date" disabled class="form-input" />
            </div>

            <!-- 附件上传区域 - 新增和编辑时显示 -->
            <div v-if="modalType !== 'view'" class="form-item full-width">
              <label>附件上传</label>
              <div class="file-upload-area">
                <div
                  class="file-upload-box"
                  @dragover.prevent
                  @drop.prevent="handleFileDrop"
                  @click="triggerFileInput"
                >
                  <input
                    type="file"
                    ref="fileInput"
                    multiple
                    accept="image/*,.pdf"
                    @change="handleFileSelect"
                    style="display: none;"
                  />
                  <div class="upload-icon">📁</div>
                  <p>点击选择文件或拖拽文件到此处上传</p>
                  <p class="upload-hint">支持图片和PDF格式，最多可上传5个文件</p>
                </div>

                <!-- 已选择的文件列表 -->
                <div v-if="selectedFiles.length > 0" class="selected-files">
                  <div
                    v-for="(file, index) in selectedFiles"
                    :key="index"
                    class="file-item"
                  >
                    <span class="file-name">{{ file.name }}</span>
                    <span class="file-size">({{ formatFileSize(file.size) }})</span>
                    <button
                      type="button"
                      @click="removeFile(index)"
                      class="remove-file-btn"
                    >×</button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 附件显示区域 - 查看时显示 -->
            <div v-if="modalType === 'view' && currentHouse.attachments && currentHouse.attachments.length > 0" class="form-item full-width">
              <label>附件</label>
              <div class="attachments-view">
                <div
                  v-for="(attachment, index) in currentHouse.attachments"
                  :key="index"
                  class="attachment-item"
                >
                  <div v-if="isImage(attachment.url)" class="image-attachment">
                    <img :src="attachment.url" :alt="attachment.name" @click="previewImage(attachment.url)">
                  </div>
                  <div v-else class="file-attachment">
                    <div class="file-icon">📄</div>
                    <div class="file-info">
                      <div class="file-name">{{ attachment.name }}</div>
                      <div class="file-size">{{ formatFileSize(attachment.size) }}</div>
                    </div>
                    <a :href="attachment.url" :download="attachment.name" class="download-link">下载</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="modalType !== 'view'" class="modal-footer">
          <button @click="closeModal" class="btn-cancel">取消</button>
          <button @click="handleSave" class="btn-save">保存</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="cancelDelete">
      <div class="modal-content delete-confirm-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="cancelDelete" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <p v-if="deleteType === 'single'">确定要删除房屋 "{{ deleteTarget.code }}" 吗？</p>
          <p v-else>确定要删除选中的 {{ selectedHouses.length }} 个房屋吗？</p>
        </div>
        <div class="modal-footer">
          <button @click="cancelDelete" class="btn-cancel">取消</button>
          <button @click="confirmDelete" class="btn-delete">删除</button>
        </div>
      </div>
    </div>

    <!-- 导出选项弹窗 -->
    <div v-if="showExportModal" class="modal-overlay" @click="closeExportModal">
      <div class="modal-content export-modal" @click.stop>
        <div class="modal-header">
          <h3>导出选项</h3>
          <button @click="closeExportModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="export-options">
            <h4>导出内容</h4>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input type="checkbox" v-model="exportOptions.includeOwner" />
                包含业主姓名
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="exportOptions.includePayment" />
                包含缴费状态
              </label>
            </div>

            <h4>导出格式</h4>
            <div class="radio-group">
              <label class="radio-item">
                <input type="radio" v-model="exportOptions.format" value="tree" />
                树状结构 (小区 - 楼栋 - 单元)
              </label>
              <label class="radio-item">
                <input type="radio" v-model="exportOptions.format" value="flat" />
                平面表格
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeExportModal" class="btn-cancel">取消</button>
          <button @click="confirmExport" class="btn-export-confirm">导出</button>
        </div>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="showImagePreview" class="image-preview-modal" @click="closeImagePreview">
      <div class="image-preview-content" @click.stop>
        <img :src="imagePreviewUrl" alt="预览图片">
        <button @click="closeImagePreview" class="close-preview-btn">×</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import * as XLSX from 'xlsx'
import {addHouse, getHouseInfo} from "@/api/house"
import {ElMessage} from "element-plus";

// 响应式数据
const searchForm = ref({
  houseCode: '',        // 房屋编号
  houseStatus: '',      // 房屋状态
  communityName: '',    // 小区名称
  unitNumber: '',       // 单元号
  floorNumber: '',      // 楼层
  housePurpose: ''      // 房屋用途
})

// 新增附件相关数据
const selectedFiles = ref([])
const fileInput = ref(null)
const imagePreviewUrl = ref('')
const showImagePreview = ref(false)

//获取房屋数据
const houses = ref([])
const loading = ref(false)
const filteredHouses = ref( [])
const fetchHouseData = async () => {
  loading.value = true
  try {
    const response = await getHouseInfo()
    houses.value = response.data || []
    filteredHouses.value = [...houses.value]
    updatePagination()
  }catch ( error){
    console.error( "获取房屋数据失败",error)
  }finally {
    loading.value = false
  }
}

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalPages: 1,
  total: 0
})

const showModal = ref(false)
const showExportModal = ref(false)
const modalType = ref('add') // 'add', 'edit', 'view'
const currentHouse = ref({})
const gotoPage = ref('')

// 导出选项
const exportOptions = ref({
  includeOwner: false,
  includePayment: false,
  format: 'tree' // 'tree' 或 'flat'
})

// 新增的状态变量
const operationMode = ref('add') // 'add', 'edit', 'delete'
const selectedHouses = ref([])
const showDeleteConfirm = ref(false)
const deleteType = ref('single') // 'single', 'batch'
const deleteTarget = ref({})

// 计算属性
const modalTitle = computed(() => {
  switch (modalType.value) {
    case 'add': return '新增房屋'
    case 'edit': return '编辑房屋'
    case 'view': return '查看房屋详情'
    default: return ''
  }
})

const paginatedHouses = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredHouses.value.slice(start, end)
})

const visiblePages = computed(() => {
  const current = pagination.value.currentPage
  const total = pagination.value.totalPages
  const pages = []

  for (let i = Math.max(1, current - 2); i <= Math.min(total, current + 2); i++) {
    pages.push(i)
  }

  return pages
})

const isAllSelected = computed(() => {
  return paginatedHouses.value.length > 0 &&
      paginatedHouses.value.every(house => selectedHouses.value.includes(house.id))
})

// 获取状态样式类
const getStatusClass = (status) => {
  return {
    'status-badge': true,
    'status-occupied': status === 1,
    'status-vacant': status === 0
  }
}

// 获取缴费状态文本
const getPaymentStatusText = (house) => {
  if (house.houseStatus === 0) {
    return '暂无'
  }
  return house.paymentStatus === 'overdue' ? '欠费' : '正常'
}

// 获取缴费状态样式类
const getPaymentStatusClass = (house) => {
  if (house.houseStatus === 0) {
    return {
      'payment-status': true,
      'payment-none': true
    }
  }

  return {
    'payment-status': true,
    'payment-overdue': house.paymentStatus === 'overdue',
    'payment-normal': true
  }
}

// 方法
const updatePagination = () => {
  pagination.value.total = filteredHouses.value.length
  pagination.value.totalPages = Math.ceil(filteredHouses.value.length / pagination.value.pageSize)
  if (pagination.value.currentPage > pagination.value.totalPages) {
    pagination.value.currentPage = 1
  }
}

const handleSearch = () => {
  filteredHouses.value = houses.value.filter(house => {
    return (
        // 房屋编号模糊匹配
        (!searchForm.value.houseCode || house.houseCode.includes(searchForm.value.houseCode)) &&

        // 房屋状态精确匹配
        (searchForm.value.houseStatus === '' || house.houseStatus == searchForm.value.houseStatus) &&

        // 小区名称模糊匹配
        (!searchForm.value.communityName || house.communityName.includes(searchForm.value.communityName)) &&

        // 单元号精确匹配
        (!searchForm.value.unitNumber || house.unitNumber === searchForm.value.unitNumber) &&

        // 楼层精确匹配
        (!searchForm.value.floorNumber || house.floorNumber === searchForm.value.floorNumber) &&

        // 房屋用途模糊匹配
        (!searchForm.value.housePurpose || (house.housePurpose && house.purpose.includes(searchForm.value.housePurpose)))
    )
  })
  pagination.value.currentPage = 1
  selectedHouses.value = []
  updatePagination()
}

const handleReset = () => {
  searchForm.value = {
    houseCode: '',
    houseStatus: '',
    communityName: '',
    unitNumber: '',
    floorNumber: '',
    housePurpose: ''
  }
  filteredHouses.value = [...houses.value]
  pagination.value.currentPage = 1
  selectedHouses.value = []
  updatePagination()
}

const handleAdd = () => {
  operationMode.value = 'add'
  selectedHouses.value = []
  modalType.value = 'add'
  const now = new Date().toISOString().split('T')[0]
  currentHouse.value = {
    id: Date.now(),
    code: '',
    houseName: '',
    community: '',
    unit: '',
    floors: '',
    room: '',
    status: 0,
    paymentStatus: 'normal',
    purpose: '',
    area: '',
    createBy: 'admin',
    updateBy: 'admin',
    createTime: now,  // 当前日期
    updateTime: now,  // 当前日期
    // 拆分attachments为产权证明和户型图
    propertyProofUrl: '', // 从attachments中提取
    floorPlanPath: '', // 从attachments中提取
    // 其他后端默认字段前端可省略，由后端赋值
  }
  selectedFiles.value = [] // 清空已选择的文件
  showModal.value = true
}

const handleSave = async () => {
  // 修复：正确处理缴费状态逻辑
  if (currentHouse.value.houseStatus === 0) {
    currentHouse.value.paymentStatus = 'normal';
  }

  try {
    // 处理附件上传（模拟上传过程）
    if (selectedFiles.value.length > 0) {
      // 模拟上传附件并生成URL
      const attachments = selectedFiles.value.map(file => ({
        name: file.name,
        size: file.size,
        type: file.type,
        url: URL.createObjectURL(file) // 在实际应用中，这里应该是上传到服务器后返回的URL
      }));

      currentHouse.value.attachments = attachments;
    }

    await addHouse(currentHouse.value);
    ElMessage.success('添加成功');

    // 更新数据列表
    if (modalType.value === 'add') {
      houses.value.push({...currentHouse.value});
      filteredHouses.value.push({...currentHouse.value});
    } else if (modalType.value === 'edit') {
      const index = houses.value.findIndex(house => house.id === currentHouse.value.id);
      if (index !== -1) {
        houses.value[index] = {...currentHouse.value};
      }
      const filteredIndex = filteredHouses.value.findIndex(house => house.id === currentHouse.value.id);
      if (filteredIndex !== -1) {
        filteredHouses.value[filteredIndex] = {...currentHouse.value};
      }
    }

    // 清空已选择的文件
    selectedFiles.value = [];
    updatePagination();
    closeModal();
  } catch(error) {
    console.error('添加失败', error);
    ElMessage.error('添加失败');
  }
}

const handleModeChange = (mode) => {
  operationMode.value = mode
  selectedHouses.value = []
}

const handleEdit = (house) => {
  modalType.value = 'edit'
  currentHouse.value = { ...house ,
    updateTime: new Date().toISOString().split('T')[0] ,
    createTime: house.createTime}
  selectedFiles.value = [] // 清空已选择的文件
  showModal.value = true
}

const handleView = (house) => {
  modalType.value = 'view'
  currentHouse.value = { ...house,
   updateTime: house.updateTime ,
   createTime: house.createTime}
  showModal.value = true
}

const handleSingleDelete = (house) => {
  deleteType.value = 'single'
  deleteTarget.value = house
  showDeleteConfirm.value = true
}

const handleBatchDelete = () => {
  if (selectedHouses.value.length === 0) return
  deleteType.value = 'batch'
  showDeleteConfirm.value = true
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedHouses.value = paginatedHouses.value.map(house => house.id)
  } else {
    selectedHouses.value = []
  }
}

const handleExport = () => {
  showExportModal.value = true
}

const closeExportModal = () => {
  showExportModal.value = false
}

const confirmExport = () => {
  exportHousesData()
  closeExportModal.value = false
}

const exportHousesData = () => {
  // 导出当前页面显示的数据，而不是全部过滤后的数据
  const dataToExport = [...paginatedHouses.value]

  if (exportOptions.value.format === 'tree') {
    // 按树状结构组织数据
    exportTreeStructure(dataToExport)
  } else {
    // 导出平面表格
    exportFlatTable(dataToExport)
  }
}

const exportTreeStructure = (data) => {
  // 构建树状结构
  const treeData = {}

  data.forEach(house => {
    if (!treeData[house.community]) {
      treeData[house.community] = {}
    }

    const building = `${house.community}${house.floors}栋`
    if (!treeData[house.community][building]) {
      treeData[house.community][building] = {}
    }

    const unit = `${house.unit}单元`
    if (!treeData[house.community][building][unit]) {
      treeData[house.community][building][unit] = []
    }

    const rowData = {
      '房屋编码': house.code,
      '房间号': house.room,
      '房屋状态': house.status === 1 ? '入住' : '空置',
      '房屋用途': house.purpose,
      '房屋面积': house.area
    }

    if (exportOptions.value.includeOwner) {
      rowData['业主姓名'] = house.owner || ''
    }

    if (exportOptions.value.includePayment) {
      rowData['缴费状态'] = house.status === 0 ? '暂无' :
                            (house.paymentStatus === 'overdue' ? '欠费' : '正常')
    }

    treeData[house.community][building][unit].push(rowData)
  })

  // 转换为Excel格式
  const wb = XLSX.utils.book_new()

  // 创建工作表
  Object.keys(treeData).forEach(community => {
    const wsData = []
    wsData.push([community]) // 小区名称作为标题

    Object.keys(treeData[community]).forEach(building => {
      wsData.push(['', building]) // 楼栋名称

      Object.keys(treeData[community][building]).forEach(unit => {
        wsData.push(['', '', unit]) // 单元名称

        // 添加表头
        const headers = Object.keys(treeData[community][building][unit][0])
        wsData.push(['', '', '', ...headers])

        // 添加数据行
        treeData[community][building][unit].forEach(row => {
          const rowData = headers.map(header => row[header])
          wsData.push(['', '', '', ...rowData])
        })

        wsData.push([]) // 空行分隔
      })
    })

    const ws = XLSX.utils.aoa_to_sheet(wsData)
    XLSX.utils.book_append_sheet(wb, ws, community.substring(0, 31)) // 工作表名称限制31字符
  })

  // 下载文件
  XLSX.writeFile(wb, '房屋信息_树状结构.xlsx')
}

const exportFlatTable = (data) => {
  // 准备表头
  const headers = [
    '房屋编码',
    '小区',
    '单元号',
    '楼层',
    '房间号',
    '房间状态',
    '房屋用途',
    '房屋面积',
    '创建时间',
    '更新时间'
  ]

  if (exportOptions.value.includeOwner) {
    headers.splice(6, 0, '业主姓名')
  }

  if (exportOptions.value.includePayment) {
    headers.splice(headers.indexOf('房间状态') + 1, 0, '缴费状态')
  }

  // 准备数据
  const exportData = data.map(house => {
    const row = [
      house.code,
      house.community,
      house.unit,
      house.floors,
      house.room,
      house.status === 1 ? '入住' : '空置',
      house.purpose,
      house.area,
      house.createTime,
      house.updateTime
    ]

    if (exportOptions.value.includeOwner) {
      row.splice(6, 0, house.owner || '')
    }

    if (exportOptions.value.includePayment) {
      const paymentStatus = house.status === 0 ? '暂无' :
                           (house.paymentStatus === 'overdue' ? '欠费' : '正常')
      row.splice(row.indexOf(house.status === 1 ? '入住' : '空置') + 1, 0, paymentStatus)
    }

    return row
  })

  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet([headers, ...exportData])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '房屋信息')

  // 下载文件
  XLSX.writeFile(wb, '房屋信息_平面表格.xlsx')
}

const confirmDelete = () => {
  if (deleteType.value === 'single') {
    // 单个删除
    const houseId = deleteTarget.value.id
    houses.value = houses.value.filter(house => house.id !== houseId)
    filteredHouses.value = filteredHouses.value.filter(house => house.id !== houseId)
  } else {
    // 批量删除
    houses.value = houses.value.filter(house => !selectedHouses.value.includes(house.id))
    filteredHouses.value = filteredHouses.value.filter(house => !selectedHouses.value.includes(house.id))
    selectedHouses.value = []
  }

  updatePagination()
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

const cancelDelete = () => {
  showDeleteConfirm.value = false
  deleteTarget.value = {}
}

// 附件相关方法
const triggerFileInput = () => {
  if (modalType.value !== 'view') {
    fileInput.value.click()
  }
}

const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  addFiles(files)
}

const handleFileDrop = (event) => {
  if (modalType.value !== 'view') {
    const files = Array.from(event.dataTransfer.files)
    addFiles(files)
  }
}

const addFiles = (files) => {
  // 限制最多上传5个文件
  const remainingSlots = 5 - selectedFiles.value.length
  if (remainingSlots <= 0) {
    alert('最多只能上传5个文件')
    return
  }

  const filesToAdd = files.slice(0, remainingSlots)

  // 添加文件到列表
  selectedFiles.value = [...selectedFiles.value, ...filesToAdd]
}

const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const isImage = (url) => {
  return /\.(jpeg|jpg|png|gif)$/i.test(url)
}

const previewImage = (url) => {
  imagePreviewUrl.value = url
  showImagePreview.value = true
}

const closeImagePreview = () => {
  showImagePreview.value = false
  imagePreviewUrl.value = ''
}

const closeModal = () => {
  showModal.value = false
  currentHouse.value = {}
  // 清空已选择的文件
  selectedFiles.value = []
}

const goToPage = (page) => {
  pagination.value.currentPage = page
  selectedHouses.value = []
}

const goToPrevPage = () => {
  if (pagination.value.currentPage > 1) {
    pagination.value.currentPage--
    selectedHouses.value = []
  }
}

const goToNextPage = () => {
  if (pagination.value.currentPage < pagination.value.totalPages) {
    pagination.value.currentPage++
    selectedHouses.value = []
  }
}

const handleGotoPage = () => {
  const page = parseInt(gotoPage.value)
  if (page >= 1 && page <= pagination.value.totalPages) {
    pagination.value.currentPage = page
    gotoPage.value = ''
    selectedHouses.value = []
  }
}

// 生命周期
onMounted(() => {
  fetchHouseData()
})
</script>
<style scoped>
/* 基础布局样式 */
.personnel-management {
  width: 100%;
  background-color: rgba(255, 255, 255, 1);
  padding: 30px 30px;
  box-sizing: border-box;
  overflow: hidden;
  border-radius: 0 15px 15px 15px;
}

/* 页面标题 */
.page-title {
  color: rgba(231, 59, 69, 1);
  font-size: 18px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  margin: 0 0 20px 0;
  line-height: 25px;
}

/* 搜索筛选区域 */
.search-filters {
  margin-bottom: 6px;
}

.search-item {
  display: block;
  margin-bottom: 5px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  width: 1527px;
  height: 32px;
}

/* 统一的输入框和选择框样式 */
.input-field, .select-field {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  width: 180px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(153, 153, 153, 1);
  box-sizing: border-box;
  line-height: 20px;
}

.input-field:focus, .select-field:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
  color: rgba(0, 0, 0, 1);
}

.input-field::placeholder {
  color: rgba(153, 153, 153, 1);
}

/* 统一的按钮样式 */
.btn-primary {
  background-color: rgba(231, 59, 69, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
}

.btn-add {
  background-color: rgba(252, 235, 236, 1);
  border-radius: 19px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(231, 59, 69, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-add:hover {
  background-color: rgba(248, 220, 222, 1);
}

.btn-export {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-export:hover {
  background-color: rgba(245, 245, 245, 1);
}

.btn-batch-delete {
  background-color: rgba(255, 77, 79, 1);
  border-radius: 19px;
  height: 32px;
  padding: 0 16px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-batch-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

.btn-icon {
  width: 13px;
  height: 13px;
}

/* 分割线 */
.divider {
  width: 1533px;
  height: 1px;
  background-color: rgba(237, 239, 244, 1);
  margin: 50px 0 0 0;
}

/* 操作按钮组样式 */
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin: 20px 0;
}

/* 表格样式 */
.table-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
  width: 100%;
  height: 610px;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.table-header {
  background-color: rgba(249, 248, 252, 1);
  height: 60px;
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-header th {
  color: rgba(0, 0, 0, 1);
  font-size: 16px;
  font-weight: normal;
  text-align: left;
  padding: 13px 21px;
  line-height: 20px;
}

.table-row {
  background-color: rgba(255, 255, 255, 1);
  height: 55px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-row td {
  color: rgba(102, 102, 102, 1);
  font-size: 16px;
  font-weight: normal;
  padding: 10px 21px;
  line-height: 20px;
  white-space: nowrap;
}

/* 复选框样式 */
.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 状态标签样式 */
.status-badge {
  padding: 2px 13px;
  border-radius: 2px;
  font-size: 12px;
  line-height: 17px;
  display: inline-block;
  height: 20px;
  box-sizing: border-box;
}

.status-occupied {
  background-color: #51cf4d; /* 绿色 */
  color: #fdfcfc;
}

.status-vacant {
  background-color: #d3d3d3; /* 灰色 */
  color: #333;
}

/* 缴费状态标签样式 */
.payment-status {
  padding: 2px 13px;
  border-radius: 2px;
  font-size: 12px;
  line-height: 17px;
  display: inline-block;
  height: 20px;
  box-sizing: border-box;
}

.payment-normal {
  background-color: #51cf4d; /* 绿色 */
  color: #fdfcfc;
}

.payment-overdue {
  background-color: #ff4d4f; /* 红色 */
  color: #fff;
}

.payment-none {
  background-color: #d3d3d3; /* 灰色 */
  color: #333;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 43px;
  align-items: center;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn img {
  width: 13px;
  height: 13px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.pagination-info {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
}

.pagination-btn {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  min-width: 32px;
  height: 32px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled) {
  background-color: rgba(249, 248, 252, 1);
}

.pagination-btn.active {
  background-color: rgba(231, 59, 69, 1);
  color: white;
  border-color: rgba(231, 59, 69, 1);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-goto {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
  margin-left: 20px;
}

.goto-input {
  width: 50px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px;
  font-size: 14px;
  text-align: center;
  line-height: 20px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.export-modal {
  width: 500px;
}

.delete-confirm-modal {
  width: 400px;
  max-height: none;
  overflow-y: visible;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(237, 239, 244, 1);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(231, 59, 69, 1);
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: rgba(102, 102, 102, 1);
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: rgba(231, 59, 69, 1);
}

.modal-body {
  padding: 20px;
}

.modal-body p {
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  line-height: 1.5;
  margin: 0;
}

.export-options h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.checkbox-group, .radio-group {
  margin-bottom: 20px;
}

.checkbox-item, .radio-item {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.checkbox-item input, .radio-item input {
  margin-right: 8px;
  vertical-align: middle;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  font-weight: 500;
  line-height: 20px;
}

.form-input {
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 1);
  line-height: 20px;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
}

.form-input:disabled {
  background-color: rgba(249, 248, 252, 1);
  color: rgba(153, 153, 153, 1);
  cursor: not-allowed;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid rgba(237, 239, 244, 1);
}

.btn-cancel {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  line-height: 20px;
}

.btn-save, .btn-export-confirm {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-delete {
  background-color: rgba(255, 77, 79, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-cancel:hover {
  background-color: rgba(249, 248, 252, 1);
}

.btn-save:hover, .btn-export-confirm:hover {
  background-color: rgba(207, 53, 63, 1);
}

.btn-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

/* 文件上传区域样式 */
.file-upload-area {
  width: 100%;
}

.file-upload-box {
  border: 2px dashed #d8d8d8;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.file-upload-box:hover {
  border-color: #e73b45;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.upload-hint {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.selected-files {
  margin-top: 15px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 8px;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  color: #999;
  font-size: 12px;
  margin: 0 10px;
}

.remove-file-btn {
  background: none;
  border: none;
  color: #e73b45;
  font-size: 18px;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-file-btn:hover {
  background-color: #f0f0f0;
  border-radius: 50%;
}

/* 附件查看样式 */
.attachments-view {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.attachment-item {
  width: 100%;
}

.image-attachment img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #eee;
}

.file-attachment {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.file-icon {
  font-size: 32px;
  margin-right: 10px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.download-link {
  color: #e73b45;
  text-decoration: none;
  font-size: 14px;
}

.download-link:hover {
  text-decoration: underline;
}

.full-width {
  grid-column: span 2;
}

/* 图片预览模态框 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.image-preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.image-preview-content img {
  max-width: 100%;
  max-height: 80vh;
  border: 2px solid white;
  border-radius: 4px;
}

.close-preview-btn {
  position: absolute;
  top: -40px;
  right: 0;
  background: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .full-width {
    grid-column: span 1;
  }
}
</style>
